package com.neusoft.bizcore.notice.notification.converter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.notice.constant.NoticeConsts;
import com.neusoft.bizcore.notice.notification.dto.NoticeRecordDTO;
import com.neusoft.bizcore.notice.notification.model.NoticeRecord;
import com.neusoft.bizcore.notice.notification.repository.NoticeRecordRepository;
import com.neusoft.bizcore.web.dto.AbstractConverter;

@Component
public class NoticeRecordConverter extends AbstractConverter<NoticeRecord, NoticeRecordDTO> {
    @Autowired
    private NoticeRecordRepository noticeRepository;

    @Autowired
    private NoticeRecordMailConverter mailConverter;

    @Autowired
    private NoticeRecordSystemConverter systemConverter;

    @Override
    public NoticeRecord toModel(final NoticeRecordDTO dto) {
        NoticeRecord model;
        if (dto.isNew()) {
            model = new NoticeRecord();
        } else {
            model = this.noticeRepository.getOne(dto.getId());
        }
        model.setAppCode(dto.getAppCode());
        final List<String> types = dto.getType();
        if ((types != null) && !types.isEmpty()) {
            final StringBuffer buffertype = new StringBuffer();
            types.forEach(t -> {
                buffertype.append(t.trim() + NoticeConsts.SPLIT_COMMA);
            });
            model.setType(buffertype.toString());
        }
        if (dto.getMail() != null) {
            model.setMail(this.mailConverter.toModel(dto.getMail()));
        }
        if (dto.getSystem() != null) {
            model.setSystem(this.systemConverter.toModel(dto.getSystem()));
        }
        model.setTitle(dto.getTitle());

        return model;
    }

    @Override
    public NoticeRecordDTO toDTO(final NoticeRecord model, final boolean forListView) {

        final NoticeRecordDTO dto = new NoticeRecordDTO();

        dto.setId(model.getId());
        dto.setAppCode(model.getAppCode());
        dto.setCreateTime(model.getCreateTime());
        final List<String> noticeTypes =
                new ArrayList<>(Arrays.asList(model.getType().split(NoticeConsts.SPLIT_COMMA)));
        dto.setType(noticeTypes);
        if (model.getMail() != null) {
            dto.setMail(this.mailConverter.toDTO(model.getMail()));
        }
        if (model.getSystem() != null) {
            dto.setSystem(this.systemConverter.toDTO(model.getSystem()));
        }
        dto.setTitle(model.getTitle());
        return dto;
    }
}
